import { DATETIMEFORMAT, pageOpeTypeEnum } from '@/common';
import { CategoryCascader, getClassViewData } from '@/components/CategoryCascader';
import { SourceSelectModal } from '@/components/SourceSelect';
import { StudyObjectSelect } from '@/components/StudyObjectSelect';
import ViewLoading from '@/components/ViewLoading';
import YmCollaPanes from '@/components/YmCollaPanes';
import { useAppSelector } from '@/redux/store';
import { App, Button, DatePicker, Form, Input, Radio, Select, Space, TreeSelect } from 'antd';
import type { RangePickerProps } from 'antd/es/date-picker';
import dayjs from 'dayjs';
import { cloneDeep, isEmpty } from 'lodash-es';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { useYmAliOss, YmUpload } from 'ym-design';
import {
  dealWidthStudyTemplate,
  getParentCode,
  pictextContentToPicTextContent,
  sourceModalChange,
  studyPlanTypeOptions,
  useEntListSelectTreeProps,
  vedioIdOrVideoInfoTransformToVideoList,
} from './common';
import { IStudyPackage, StudyPlanChildProps, StudyPlanChildRef } from './interface';

import { createFixedStudyPlan, getCurrLocation, getFixedStudyPlanDetail } from '@/api/Plan';
import Source from '@/components/SourceSelect/Entity/Source';
import { requestParamsFormat } from '@/utils';
import { useNavigate } from 'react-router-dom';
import { v4 as uuid } from 'uuid';
import OStyle from './components/index.less';
import { positionInfoValue } from './components/interface';
import PositionInfo from './components/PositionInfo';
import StudyPackage from './components/StudyPackage';

const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 10 },
};

const AddFixedStudyPlan = forwardRef<StudyPlanChildRef, StudyPlanChildProps>((props, ref) => {
  const {
    message,
    modal: { confirm },
  } = App.useApp();
  const navigator = useNavigate();
  const [form] = Form.useForm();
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt); //organizationType 1:协会，0：企业
  const { loginRole } = useAppSelector((state) => state.loginUser);
  const { tradeMap } = useAppSelector((state) => state.commonData);
  const {
    onStudyPlanMethodChange,
    studyPlanType,
    onStudyPlanTypeChange,
    onSubSuccess,
    onSubError,
    type,
    planCourseId,
    previewDetail,
  } = props;
  let learnMethod = props.learnMethod;
  const [collPanesActiveKeys, setCollPanesActiveKeys] = useState([3, 4]);
  const [modalOpen, setModalOpen] = useState<number>();
  const [loading, setLoading] = useState(false);
  const [classFormItemProps, initRef] = CategoryCascader.useFieldLevelTwo();

  // 使用aliyunoss进行操作
  const customRequest = useYmAliOss();

  //学习对象企业配置
  const EntSelectTree = useEntListSelectTreeProps({
    onSuccess(data) {
      const entList = form.getFieldsValue().entList;
      if (!entList) {
        // 没有就是需要默认给全部
        form.setFieldsValue({
          entList: data.map(({ title, id }) => ({
            entId: id,
            entName: title,
          })),
        });
      }
    },
  });

  //处理提交数据
  const dealWidthFormValues = (values: any, issue: number) => {
    let finalValue: any = {};
    const {
      studyPackageList,
      studyTime,
      cover,
      studyMethod,
      positionInfoDto,
      modelType,
      title,
      classId,
      entList,
      studyObject,
      objectType,
      serviceNumType,
    } = values;
    //处理学习时间
    const startTime = studyTime[0].format(DATETIMEFORMAT);
    const endTime = studyTime[1].format(DATETIMEFORMAT);
    //封面
    if (!isEmpty(cover)) {
      finalValue.cover = cover[0].response || cover[0].url; // url：编辑时回显的是url
    }

    if (organizationType === 1) {
      //协会
      //--学习对象
      finalValue.objectType = objectType;
      if (objectType === 1) {
        //企业范围
        finalValue.entList = entList;
      } else if (objectType === 4) {
        //服务号范围
        finalValue.serviceNumType = serviceNumType;
      }
      //--学习模式 studyMethod，学习位置 positionInfoDto，学习方式 modelType
      finalValue.studyMethod = studyMethod;
      //线下培训，位置信息
      if (studyMethod === 200) {
        finalValue.positionInfoDto = requestParamsFormat(positionInfoDto);
      } else {
        finalValue.modelType = modelType;
      }
    }

    // 处理学习包数据
    const clStudyPackageList = cloneDeep(studyPackageList);
    const newStudyPackageList = clStudyPackageList.reduce((prev: any[], curr: any, index: number, array: any[]) => {
      const { studyList } = curr;
      delete curr.sourceType;
      //去除id
      delete curr.id;
      const studyAndExamObj = studyList.reduce(
        (sePrev: { studyList: any[]; examList: any[] }, seCurr: any) => {
          const { type, origin } = seCurr;

          seCurr.sourceType = Number(seCurr.sourceType);
          seCurr.type = Number(seCurr.type);
          //课件包是没有origin字段的
          if (!isEmpty(origin)) {
            if (String(type) !== '300') {
              // seCurr.picTextContent = origin.picTextContent || undefined;
              // seCurr.pictextContent = origin.pictextContent || undefined;
              seCurr.picUrl = origin.picUrl || undefined;
              seCurr.vedioId = origin.vedioId || undefined;
              seCurr.vedioInfo = origin.vedioInfo || undefined;
              seCurr.videoList = vedioIdOrVideoInfoTransformToVideoList(origin);
              seCurr.picTextContent = pictextContentToPicTextContent(origin);
            }
            delete seCurr.origin;
          }

          if (String(type) === '300') {
            sePrev.examList.push(seCurr);
          } else {
            sePrev.studyList.push({
              ...seCurr,
              videoList: vedioIdOrVideoInfoTransformToVideoList(seCurr),
              picTextContent: pictextContentToPicTextContent(seCurr),
            });
          }
          return sePrev;
        },
        { examList: [], studyList: [] },
      );
      prev.push({
        ...curr,
        studyList: studyAndExamObj.studyList,
        examList: studyAndExamObj.examList,
      });
      return prev;
    }, []);
    const notNullStudyPackageList = requestParamsFormat(newStudyPackageList);
    finalValue = {
      // form字段
      ...finalValue,
      startTime,
      endTime,
      title,
      classId: Array.isArray(classId) ? classId[1] : classId,
      studyObject,
      // 其他字段
      entId,
      issueObjectType: 400, //发布对象类型 100所有(全平台) 200关注我的 300加入的 400指定对象
      addSource: organizationType === 1 ? 2 : 1, //1企业2政协
      studyPackageList: notNullStudyPackageList,
      issue, //1：发布，0：保存
      isCharge: notNullStudyPackageList.findIndex((item: IStudyPackage) => item.isCharge) > -1 ? 1 : 0, //是否有收费内容0否,1是
    };
    return finalValue;
  };

  const _sub = (issue: number) => {
    form
      .validateFields()
      .then((values) => {
        console.log('--AddFixedStudyPlan--form--values--:', values);
        if (isEmpty(values.studyPackageList)) return message.warning('请先添加计划内容');
        if (!dayjs(values.studyTime[0]).isAfter(dayjs())) {
          return message.warning('学习开始时间必须大于当前时间');
        }
        const subValue = dealWidthFormValues(values, issue);
        if (type === pageOpeTypeEnum['edit']) {
          //编辑
          subValue.guid = planCourseId;
        }
        console.log('---subValue--:', subValue);
        setLoading(true);
        createFixedStudyPlan(subValue)
          .then((res: any) => {
            const { code, data, msg } = res;
            // console.log('--res--:', res);
            if (code === '200') {
              if (data === 1) {
                confirm({
                  title: '发布失败',
                  content: msg,
                  centered: true,
                  okText: '前往',
                  onOk: () => {
                    if (loginRole == '1' || loginRole == '0') {
                      navigator('/safeService/buyService');
                    } else {
                      message.warning('您暂无权限，请联系企业管理人员！');
                    }
                  },
                });
              } else if (data.promptMessage) {
                confirm({
                  title: '发布成功',
                  content: data.promptMessage,
                  centered: true,
                  okText: '前往',
                  onOk: () => {
                    if (loginRole == '1' || loginRole == '0') {
                      navigator('/safeService/bitAllocation');
                    } else {
                      message.warning('您暂无权限，请联系企业管理人员！');
                    }
                  },
                });
              } else {
                message.success((type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + '成功');
                onSubSuccess?.();
              }
            }
          })
          .finally(() => {
            setLoading(false);
          })
          .catch((err) => {
            console.log('--AddFixedStudyPlan--createFixedStudyPlan--err--:', err);
          });
      })
      .catch((err) => {
        onSubError?.();
        console.log('--AddFixedStudyPlan--form--err--:', err);
      });
  };

  //发布
  const onSubPublish = () => {
    _sub(1);
  };

  //保存
  const onSubSave = () => {
    _sub(0);
  };

  useImperativeHandle(ref, () => ({
    onSubPublish,
    onSubSave,
  }));

  useEffect(() => {
    // 初始化获取当前定位
    if (type === pageOpeTypeEnum['add']) {
      if (organizationType === 1) {
        //协会
        form.setFieldsValue({ objectType: 1, studyMethod: '100', modelType: 1 });
      }
      learnMethod = '100';
      getCurrLocation({ entId }).then((res) => {
        const data = res.data as positionInfoValue;
        form.setFieldValue('positionInfoDto', data);
      });
      if (!isEmpty(previewDetail)) {
        //计划模板进来
        // console.log('--AddFixedStudyPlan--previewDetail--:', previewDetail);
        const { name, faceImg, guid, isCharge } = previewDetail;
        const initialFormVal: any = {
          title: name,
          cover: faceImg ? [{ uid: uuid(), url: faceImg }] : undefined,
          studyMethod: '100',
        };
        form.setFieldsValue(initialFormVal);
        dealWidthStudyTemplate(guid, isCharge).then((studyPackageList) => {
          form.setFieldValue('studyPackageList', studyPackageList);
        });
      }
    } else if (type === pageOpeTypeEnum['edit'] && planCourseId) {
      setLoading(true);
      getFixedStudyPlanDetail(planCourseId)
        .then((res: any) => {
          const { data } = res;
          console.log('--AddFixedStudyPlan--edit--data--:', data);
          const initialFormValue: any = {};
          const {
            studyMethod,
            positionInfoDto,
            modelType,
            objectType,
            entList,
            serviceNumType,
            startTime,
            endTime,
            cover,
            studyPackageList,
            title,
            classId,
            studyObject,
            isCharge,
          } = data;
          if (organizationType === 1) {
            //协会
            //--学习对象
            initialFormValue.objectType = objectType;
            if (objectType === 1) {
              //企业范围
              initialFormValue.entList = entList;
            } else if (objectType === 4) {
              //服务号范围
              initialFormValue.serviceNumType = serviceNumType;
            }
            //--学习模式 studyMethod，学习位置 positionInfoDto，学习方式 modelType
            initialFormValue.studyMethod = studyMethod;
            //线下培训，位置信息
            if (studyMethod === 200) {
              initialFormValue.positionInfoDto = positionInfoDto;
            } else {
              initialFormValue.modelType = modelType;
            }
          }
          //学习时间
          const studyTime = [dayjs(startTime, DATETIMEFORMAT), dayjs(endTime, DATETIMEFORMAT)];
          //封面
          if (!isEmpty(cover)) {
            initialFormValue.cover = [{ uid: uuid(), url: cover }];
          }
          //学习包
          const newStudyPackageList = studyPackageList.reduce(
            (prev: IStudyPackage[], curr: IStudyPackage, index: number, array: IStudyPackage[]) => {
              const { studyList, examList, packageType, sourceType } = curr;
              let newStudyList: any[] = studyList || [];
              if (!isEmpty(examList)) {
                newStudyList = [...newStudyList, ...examList!];
              }
              prev.push({
                id: uuid(),
                studyList: newStudyList,
                packageType,
                sourceType,
                isCharge,
                pageType: 'edit',
              });
              return prev;
            },
            [],
          );

          form.setFieldsValue({
            ...initialFormValue,
            studyTime,
            studyPackageList: newStudyPackageList,
            title,
            studyObject,
          });
          learnMethod = '100';
          form.setFieldValue('studyMethod', '100');
          // 分类回显
          getClassViewData().then((data) => {
            // console.log('--data--:', data);
            const parentCode = getParentCode(data, classId);
            form.setFieldValue('classId', [parentCode, classId]);
          });
        })
        .finally(() => {
          setLoading(false);
        })
        .catch((err) => {
          console.log('--AddFixedStudyPlan--getFixedStudyPlanDetail--err--:', err);
        });
    }
  }, [type, organizationType, planCourseId]);

  //学习时间选择限制
  const disabledRangeTime: RangePickerProps['disabledTime'] = (_, type) => {
    // if (type === 'start') {}
    const range = (start: number, end: number) => {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    };
    const curHour = dayjs().get('hour');
    const curMin = dayjs().get('minute');

    return {
      disabledHours: () => range(0, 24).splice(0, curHour),
      disabledMinutes: () => range(0, 60).splice(0, curMin),
    };
  };

  //添加学习包
  const handleSourceModalChange = (values: Source[], menuActiveKey: string) => {
    const sourceList: IStudyPackage[] = form.getFieldValue('studyPackageList') || [];
    sourceModalChange(values, menuActiveKey, sourceList)
      .then((newSourceList: IStudyPackage[]) => {
        console.log('newSourceListnewSourceListnewSourceList', newSourceList);
        form.setFieldValue('studyPackageList', newSourceList);
      })
      .catch((errMsg) => {
        message.warning(errMsg);
      });
  };

  return (
    <>
      <ViewLoading show={loading} />
      <Form layout="horizontal" labelAlign="right" form={form} {...formItemLayout}>
        <YmCollaPanes
          collPanesActiveKeys={collPanesActiveKeys}
          // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
          paneKey={3}
          collapsible={false}
          headerTitle="基本信息"
        >
          {organizationType === 1 && (
            <>
              <Form.Item label="学习模式" name="studyMethod" rules={requireRules('请选择学习模式')}>
                <Radio.Group
                  defaultValue={learnMethod}
                  onChange={(e) => {
                    onStudyPlanMethodChange(e.target.value);
                    console.log(e.target.value, learnMethod, '打印看看现在是什么a');
                  }}
                  disabled={type !== pageOpeTypeEnum['add']}
                >
                  <Radio value="100">线上学习</Radio>
                  <Radio value="200">线下培训</Radio>
                </Radio.Group>
              </Form.Item>
            </>
          )}
          <Form.Item label="类型" required>
            <Space size={16}>
              <Select
                style={{ width: '120px' }}
                value={studyPlanType}
                onChange={onStudyPlanTypeChange}
                disabled={type !== pageOpeTypeEnum['add'] || !isEmpty(previewDetail)}
                options={studyPlanTypeOptions}
              />
            </Space>
          </Form.Item>
          {organizationType === 1 && (
            <>
              {/* <Form.Item label="学习模式" name="studyMethod" rules={requireRules('请选择学习模式')}>
                <Radio.Group disabled={type !== pageOpeTypeEnum['add']}>
                  <Radio value={100}>线上学习</Radio>
                  <Radio value={200}>线下培训</Radio>
                </Radio.Group>
              </Form.Item> */}
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) => prevValues.studyMethod !== currentValues.studyMethod}
              >
                {({ getFieldValue }) =>
                  getFieldValue('studyMethod') === 200 ? (
                    <Form.Item
                      label="学习位置"
                      name="positionInfoDto"
                      rules={requireRules('请选择学习位置')}
                      wrapperCol={{ span: 19 }}
                    >
                      <PositionInfo />
                    </Form.Item>
                  ) : (
                    <Form.Item label="学习方式" name="modelType" rules={requireRules('请选择学习方式')}>
                      <Radio.Group disabled={type !== pageOpeTypeEnum['add']}>
                        <Radio value={1}>必学</Radio>
                        <Radio value={2}>选学</Radio>
                      </Radio.Group>
                    </Form.Item>
                  )
                }
              </Form.Item>
            </>
          )}
          <Form.Item label="学习时间" name="studyTime" rules={requireRules('请输入学习时间')}>
            <DatePicker.RangePicker
              format="YYYY-MM-DD HH:mm"
              showTime={{ format: 'HH:mm' }}
              disabledDate={(date) => {
                return date.isBefore(dayjs().startOf('day'));
              }}
              disabledTime={disabledRangeTime}
            ></DatePicker.RangePicker>
          </Form.Item>
          <Form.Item label="计划名称" name="title" rules={requireRules('请输入计划名称')}>
            <Input showCount maxLength={18} placeholder="请输入"></Input>
          </Form.Item>

          <Form.Item label="分类" name="classId" {...classFormItemProps} rules={requireRules('请选择分类')}>
            <CategoryCascader />
          </Form.Item>
          {organizationType === 1 ? (
            <Form.Item label="学习对象" required wrapperCol={{ span: 19 }}>
              <Space>
                <Form.Item name="objectType" noStyle>
                  <Select
                    options={[
                      { label: '企业范围', value: 1 },
                      { label: '服务号范围', value: 4 },
                    ]}
                  />
                </Form.Item>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) => prevValues.objectType !== currentValues.objectType}
                >
                  {({ getFieldValue }) =>
                    getFieldValue('objectType') === 1 ? (
                      <Space>
                        <Form.Item
                          name="entList"
                          noStyle
                          {...EntSelectTree.fieldProps}
                          rules={requireRules('请选择学习对象企业')}
                        >
                          <TreeSelect {...EntSelectTree.treeSelectProps}></TreeSelect>
                        </Form.Item>
                        <Form.Item name="studyObject" noStyle rules={requireRules('请选择学习对象人员')}>
                          <StudyObjectSelect optionsType={2} />
                        </Form.Item>
                      </Space>
                    ) : (
                      <>
                        <Form.Item name="serviceNumType" noStyle>
                          <Select
                            options={[
                              { label: '全部范围人员', value: 0 },
                              { label: '管辖企业人员', value: 1 },
                              { label: '非管辖企业人员', value: 2 },
                            ]}
                          />
                        </Form.Item>
                        <Form.Item noStyle>
                          <Select
                            value={1}
                            options={[
                              { label: '全部人员', value: 1, disabled: true },
                              { label: '司机', value: 4, disabled: true },
                            ]}
                          />
                        </Form.Item>
                      </>
                    )
                  }
                </Form.Item>
              </Space>
            </Form.Item>
          ) : (
            <Form.Item name="studyObject" label="学习对象" rules={requireRules('请选择学习对象人员')}>
              <StudyObjectSelect placeholder="请选择学习对象" optionsType={1} />
            </Form.Item>
          )}
          <Form.Item label="封面图">
            <Form.Item name="cover" noStyle>
              <YmUpload maxCount={1} cardWidth={140} cardHeight={140} accept="image/*" customRequest={customRequest}>
                上传图片
              </YmUpload>
            </Form.Item>
            <p className="safe-edu_upload_warning">图片宽高比例以1.875:1为宜，如：750*400</p>
          </Form.Item>
        </YmCollaPanes>
        <YmCollaPanes
          collPanesActiveKeys={collPanesActiveKeys}
          // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
          paneKey={4}
          collapsible={false}
          headerTitle="计划内容"
          contentClass={OStyle.cus_item_content}
          extra={
            !isEmpty(tradeMap) && (
              <Button
                style={{ marginRight: '16px' }}
                size="small"
                type="primary"
                shape="round"
                onClick={() => {
                  setModalOpen(Math.random());
                }}
              >
                添加
              </Button>
            )
          }
        >
          <SourceSelectModal
            openDep={modalOpen}
            preSet="学习计划"
            params={{ entId }}
            columnsRender={{ tradeMap }}
            onChange={handleSourceModalChange} //放在Form.Item里面只会识别第一个参数作为value
            // modalWidth={1176}
            // menuLeftWidth={168}
          />
          <Form.Item name="studyPackageList" noStyle>
            <StudyPackage type={type} />
          </Form.Item>
        </YmCollaPanes>
      </Form>
    </>
  );
});

export default AddFixedStudyPlan;
